package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-14
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<AdUser> query = new LambdaQueryWrapper<>();

        query.eq(AdUser::getName,dto.getName());

        AdUser one = this.getOne(query);

        if(one==null){

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt = one.getSalt();

        String s = dto.getPassword() + salt;

        String s1 = DigestUtils.md5DigestAsHex(s.getBytes());

        if(!s1.equals(one.getPassword())){

            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        Map<String, Object> claimMap = new HashMap<>();

        claimMap.put("userId", one.getId());

        claimMap.put("userName", one.getName());

        String token = AppJwtUtil.getToken(claimMap);

        Map<String,Object> map = new HashMap<>();

        one.setPhone(null);

        one.setPassword(null);

        one.setSalt(null);

        map.put("user",one);

        map.put("token",token);

        return ResponseResult.okResult(map);
    }
}
